package com.crack.nga2.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Layout;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.crack.nga2.R;
import com.crack.nga2.custom.VerticalScanView;
import com.crack.nga2.fragment.EmotionFragment;
import com.crack.nga2.fragment.PostImageFragment;
import com.crack.nga2.utils.GlobalConst;
import com.crack.nga2.volley.PostRequest;
import com.crack.nga2.volley.PostUploadRequest;
import com.crack.nga2.volley.UploadAttach;
import com.crack.nga2.volley.UploadAttachDataList;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class PostActivity extends BaseActivity implements PostImageFragment.IUpload, EmotionFragment.SelectEmotion,
        PostImageFragment.DragPositionChanged, EmotionFragment.DragEmotion {
    private EditText etTitle, etContent;
    private String action;
    private String post_content;
    private String post_subject;
    //预置内容
    private String pre_content;
    private int pid;
    private int fid;
    private int tid;
    private RequestQueue mQueue;
    private FragmentManager fragmentManager;
    private PostImageFragment postImageFragment;
    private EmotionFragment emotionFragment;
    private String auth;
    private String attach_url;
    /**
     * 当前fragment
     */
    private Fragment currentFragment;
    /**
     * 已上传图片的信息
     */
    private Map<String, Map<String, String>> uploadBitmap = new HashMap<>();

    private TextView tvAddr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        tvAddr = $(R.id.tv_addr);
        tvAddr.setText(GlobalConst.ADDR);
        mQueue = NgaApplication.getQueue();
        getIntentData();
        initViews();
        fragmentManager = getSupportFragmentManager();

    }

    private void getIntentData() {
        Intent intent = getIntent();
        action = intent.getStringExtra("action");
        pre_content = intent.getStringExtra("content");
        pid = intent.getIntExtra("pid", 0);
        fid = intent.getIntExtra("fid", 0);
        tid = intent.getIntExtra("tid", 0);
        auth = intent.getStringExtra("auth");
        attach_url = intent.getStringExtra("attach_url");
    }

    private void initViews() {
        etContent = $(R.id.edit_content);
        etTitle = $(R.id.edit_title);
        etContent.addTextChangedListener(new MyTextChangeListener());
        if (!TextUtils.isEmpty(pre_content)) {
            etContent.setText(pre_content);
        }
    }


    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.action_return:
                finishForAnimation();
                break;
            case R.id.action_post:
                post_content = etContent.getText().toString();
                post_subject = etTitle.getText().toString();
                if ("new".equals(action) && TextUtils.isEmpty(post_subject)) {
                    etTitle.setError("标题不能为空");
                    return;
                }
                if (TextUtils.isEmpty(post_content)) {
                    etContent.setError("内容不能为空");
                }
                post();
                break;
            case R.id.btn_pic:
                closeKey();
                if (postImageFragment == null) {
                    postImageFragment = new PostImageFragment();
                }
                currentFragment = postImageFragment;
                fragmentManager.beginTransaction().replace(R.id.container, postImageFragment).commit();
                break;
            case R.id.btn_emotion:
                closeKey();
                if (emotionFragment == null) {
                    emotionFragment = new EmotionFragment();
                }
                currentFragment = emotionFragment;
                fragmentManager.beginTransaction().replace(R.id.container, emotionFragment).commit();
                break;
            case R.id.post_bold:
                closeKey();
                break;
            case R.id.post_delete_line:
                if (stack.size() == 0) {
                    return;
                }
                InsertEntity entity = stack.removeLast();
                Editable editable = etContent.getEditableText();
                editable.delete(entity.start, entity.start + entity.length);
                break;
            case R.id.anonymous:

                break;
            case R.id.edit_content:
                if (currentFragment != null) {
                    fragmentManager.beginTransaction().remove(currentFragment).commit();
                    currentFragment = null;
                }
                break;
        }
    }


    private void post() {
        if (action == null) {
            Toast.makeText(this, "异常", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("step", String.valueOf(2));
        params.put("lite", "js");
        params.put("action", action);
        params.put("post_content", post_content);
        if (!TextUtils.isEmpty(post_subject)) {
            params.put("post_subject", post_subject);
        }
        if (pid != 0) {
            params.put("pid", String.valueOf(pid));
        }
        if (tid != 0) {
            params.put("tid", String.valueOf(tid));
        }
        if (fid != 0) {
            params.put("fid", String.valueOf(fid));
        }
        StringBuilder attachments = new StringBuilder();
        StringBuilder attachments_check = new StringBuilder();
        for (Map.Entry<String, Map<String, String>> entry : uploadBitmap.entrySet()) {
            Map<String, String> value = entry.getValue();
            attachments.append(value.get("attachments")).append("\t");
            attachments_check.append(value.get("attachments_check")).append("\t");
        }
        params.put("attachments", attachments.toString());
        params.put("attachments_check", attachments_check.toString());
        mQueue.add(new PostRequest(params,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("post", response);
                        Toast.makeText(PostActivity.this, "回帖成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("tag", error.getMessage());
                    }
                }));
    }

    private void closeKey() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    @Override
    public void upload(final String path, final View view) {
        Map<String, String> attachInfo = uploadBitmap.get(path);
        if (attachInfo != null) {
            //已上传
            String url = "[img]" + "./" + attachInfo.get("url") + "[/img]";
            insertToText(url);
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            PostImageFragment.ViewHolder holder = (PostImageFragment.ViewHolder) view.getTag();
            final VerticalScanView scanView = holder.scanView;
            scanView.onStart();
            String fileName = file.getName();
            String type = "image/" + fileName.substring(fileName.lastIndexOf(".") + 1);
            UploadAttach attach = new UploadAttach(file, type, 1, fid, auth);
            UploadAttachDataList list = new UploadAttachDataList();
            list.attaches = new ArrayList<>();
            list.attaches.add(attach);
            mQueue.add(new PostUploadRequest(attach_url, list, new Response.Listener<Map<String, String>>() {
                @Override
                public void onResponse(Map<String, String> response) {
                    //图片上传成功、保存信息
                    uploadBitmap.put(path, response);
                    Toast.makeText(PostActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    scanView.onStopComplete();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    scanView.onStopComplete();
                    error.printStackTrace();
                }
            }));
        }
    }

    private void insertToText(String url) {
        if (url == null)
            return;
        int index = etContent.getSelectionStart();
        Editable span = etContent.getText();
        span.insert(index, url);
        pushToStack(url, index);
    }

    private void pushToStack(String url, int index) {
        InsertEntity entity = new InsertEntity();
        entity.start = index;
        entity.length = url.length();
        entity.content = url;
        stack.addLast(entity);
        if (stack.size() > 10) {
            stack.removeFirst();
        }
    }


    @Override
    public void select(String name) {
        if (name != null) {
            insertToText(name);
        }
    }

    private int[] editContentPosition = new int[2];

    @Override
    public void dragToXY(int x, int y, String url) {
        etContent.getLocationOnScreen(editContentPosition);
        x -= editContentPosition[0];
        y -= editContentPosition[1];
        if (y < 0 || y > etContent.getHeight() || x < 0 || x > etContent.getWidth()) {
            return;
        }
        x -= etContent.getTotalPaddingLeft();
        y -= etContent.getTotalPaddingTop();
        x -= etContent.getScrollX();
        y -= etContent.getScrollY();
        Layout layout = etContent.getLayout();
        int line = layout.getLineForVertical(y);
        int offset = layout.getOffsetForHorizontal(line, x);
        etContent.setSelection(offset);
    }

    @Override
    public void completeDragEmotion(int x, int y, String url) {
        etContent.getLocationOnScreen(editContentPosition);
        x -= editContentPosition[0];
        y -= editContentPosition[1];
        if (y < 0 || y > etContent.getHeight()) {
            return;
        }
        insertToText(url);
    }

    @Override
    public void completeDrag(int x, int y, String path) {
        etContent.getLocationOnScreen(editContentPosition);
        x -= editContentPosition[0];
        y -= editContentPosition[1];
        if (y < 0 || y > etContent.getHeight() || x < 0 || x > etContent.getWidth()) {
            return;
        }
        Map<String, String> attachInfo = uploadBitmap.get(path);
        if (attachInfo != null) {
            //已上传
            String url = attachInfo.get("url");
            insertToText("[img]" + "./" + url + "[/img]");
        } else {
            Toast.makeText(PostActivity.this, "请先点击上传", Toast.LENGTH_SHORT).show();
        }
    }

    private LinkedList<InsertEntity> stack = new LinkedList<>();

    private class InsertEntity {
        int start;
        int length;
        CharSequence content;
    }

    private class MyTextChangeListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
